<!-- 正文开始 -->
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <!-- 头部操作栏 -->
            <form class="layui-form">
                <div class="layui-form lay-header">
                    <div class="toolbar">
                        <div class="layui-form-item lay-query-content">
                            <div class="lay-query-box">
                                <div class="query-lt">
                                    <div class="layui-inline">
                                        <label class="layui-form-label">类型：</label>
                                        <div class="layui-input-inline">
                                            <select name="">
                                                <option value="">类型</option>
                                                <option value="">刀具</option>
                                                <option value="">轴承</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <label class="layui-form-label">物料系列：</label>
                                        <div class="layui-input-inline">
                                            <select name="">
                                                <option value="">类型</option>
                                                <option value="">刀具</option>
                                                <option value="">轴承</option>
                                            </select>
                                        </div>
                                    </div>

                                    <div class="layui-inline">
                                        <label class="layui-form-label">状态：</label>
                                        <div class="layui-input-inline">
                                            <select name="">
                                                <option value="">类型</option>
                                                <option value="">刀具</option>
                                                <option value="">轴承</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <label class="layui-form-label">起止时间：</label>
                                        <div class="layui-input-inline">
                                            <input name="" class="layui-input" type="text" placeholder="起止时间"/>
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <label class="layui-form-label">物料名称：</label>
                                        <div class="layui-input-inline">
                                            <input name="" class="layui-input" type="text" placeholder="物料名称"/>
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <label class="layui-form-label">供应商名称：</label>
                                        <div class="layui-input-inline">
                                            <input name="" class="layui-input" type="text" placeholder="供应商名称"/>
                                        </div>
                                    </div>

                                </div>
                                <div class="query-rt">
                                    <div class="layui-inline">
                                        <button class="layui-btn" lay-filter="formSubSearchLog" lay-submit>查询</button>
                                        <button class="layui-btn color-white" lay-filter="searchReset" lay-submit
                                                type="button">
                                            重置
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="lay-btn-rows">
                        <div class="lay-btn-box">
                            <div class="lay-btn-lt">
                                <button id="productDetailBtnExport" class="layui-btn">导出</button>
                            </div>
                            <div class="lay-btn-rt">
                            </div>
                        </div>
                    </div>
                </div>
            </form>
            <!-- 表格 -->
            <table class="layui-table" id="productDetailTable" lay-filter="productDetailTable"></table>
        </div>
    </div>
</div>

<style>
    .layui-table-cell {
        height: auto;
        max-height: 80px;
    }

    .inputBorderNone {
        border: none;
        background: transparent;
        outline: none;
    }

    ::-webkit-scrollbar {
        display: none; /* Chrome Safari */
    }

    #assemblyTabContent .layui-form,
    #assemblyTabContent .layui-table-box,
    #assemblyTabContent .layui-table-body,
    #assemblyTabContent td[data-field="defaultUnit"] .layui-table-cell,
    #assemblyTabContent td[data-field="alternativeUnit"] .layui-table-cell {
        overflow: visible;
        /*padding: 0 5px;*/
    }

    #assemblyTabContent .layui-table-cell {
        padding: 0 10px;
    }

    div[lay-id="materialListAddTable"] tbody tr.materialListAddTableTrDisable {
        background-color: #e6e6e6;
    }

    div[lay-id="materialListAddTable"] tbody tr.materialListAddTableTrDisable:hover {
        background-color: #e6e6e6 !important;
    }

</style>
<!-- 表格操作列 -->
<script type="text/html" id="productDetailTableBar">
    <!--<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">修改</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>-->
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="details">详情</a>
    <a class="layui-btn layui-btn-xs" lay-event="assembly">组件BOM</a>
</script>

<!-- 表单弹窗 -->
<script type="text/html" id="productDetailForm">
    <form lay-filter="productDetailForm" class="layui-form model-form">
        <input name="id" type="hidden"/>
        <div class="layui-form-item">
            <label class="layui-form-label">创建者</label>
            <div class="layui-input-block">
                <input name="creator" placeholder="请输入创建者" type="text" class="layui-input" lay-verify="required"
                       required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">修改者</label>
            <div class="layui-input-block">
                <input name="modifier" placeholder="请输入修改者" type="text" class="layui-input" lay-verify="required"
                       required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">创建人</label>
            <div class="layui-input-block">
                <input name="creatorName" placeholder="请输入创建人" type="text" class="layui-input" lay-verify="required"
                       required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">修改人</label>
            <div class="layui-input-block">
                <input name="modifierName" placeholder="请输入修改人" type="text" class="layui-input" lay-verify="required"
                       required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">商品ID</label>
            <div class="layui-input-block">
                <input name="productId" placeholder="请输入商品ID" type="text" class="layui-input" lay-verify="required"
                       required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">物料编号</label>
            <div class="layui-input-block">
                <input name="sku" placeholder="请输入物料编号" type="text" class="layui-input" lay-verify="required"
                       required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">商品缩略图</label>
            <div class="layui-input-block">
                <input name="productPic" placeholder="请输入商品缩略图" type="text" class="layui-input" lay-verify="required"
                       required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">物料名称</label>
            <div class="layui-input-block">
                <input name="skuName" placeholder="请输入物料名称" type="text" class="layui-input" lay-verify="required"
                       required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">商品规格</label>
            <div class="layui-input-block">
                <input name="skuSpec" placeholder="请输入商品规格" type="text" class="layui-input" lay-verify="required"
                       required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">企业货号</label>
            <div class="layui-input-block">
                <input name="enterpriceCode" placeholder="请输入企业货号" type="text" class="layui-input" lay-verify="required"
                       required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">市场指导价</label>
            <div class="layui-input-block">
                <input name="marketPrice" placeholder="请输入市场指导价" type="text" class="layui-input" lay-verify="required"
                       required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">商品店铺价</label>
            <div class="layui-input-block">
                <input name="storePrice" placeholder="请输入商品店铺价" type="text" class="layui-input" lay-verify="required"
                       required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">最低活动价</label>
            <div class="layui-input-block">
                <input name="activityPrice" placeholder="请输入最低活动价" type="text" class="layui-input" lay-verify="required"
                       required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">平台供货价</label>
            <div class="layui-input-block">
                <input name="supplyPrice" placeholder="请输入平台供货价" type="text" class="layui-input" lay-verify="required"
                       required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">库存数</label>
            <div class="layui-input-block">
                <input name="stockNumber" placeholder="请输入库存数" type="text" class="layui-input" lay-verify="required"
                       required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">商品条码</label>
            <div class="layui-input-block">
                <input name="barcode" placeholder="请输入商品条码" type="text" class="layui-input" lay-verify="required"
                       required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">排序</label>
            <div class="layui-input-block">
                <input name="sortNumber" placeholder="请输入排序" type="text" class="layui-input" lay-verify="required"
                       required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">入驻企业ID</label>
            <div class="layui-input-block">
                <input name="settledCompanyId" placeholder="请输入入驻企业ID" type="text" class="layui-input"
                       lay-verify="required" required/>
            </div>
        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
            <button class="layui-btn" lay-filter="productDetailFormSubmit" lay-submit>保存</button>
        </div>
    </form>
</script>

<!--组件BOM-->
<!--assembly-->
<script type="text/html" id="assembly">
    <form lay-filter="assemblyForm" class="layui-form model-form"
          style="padding: 5px 10px 0;height: calc(100% - 5px);overflow: hidden;scrollbar-width:none;">
        <div class="open-details-box" style="height: calc(100% - 65px); overflow-y: scroll; scrollbar-width:none;">
            <!-- 表格 -->
            <table class="layui-table" id="assemblyFormTable" lay-filter="assemblyFormTable"></table>
            <div class="layui-tab" lay-filter="assemblyTable">
                <ul class="layui-tab-title" id="assemblyTabTitle"></ul>
                <div class="layui-tab-content" id="assemblyTabContent"></div>
            </div>
        </div>
        <div class="layui-form-item text-right" style="margin-top: 20px">
            <button class="layui-btn" lay-filter="assemblyFormSubmit" lay-submit type="button">保存BOM信息</button>
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
        </div>
    </form>
</script>

<!--组件BOM表单操作-->
<!--assemblyFormTableBar-->
<script type="text/html" id="assemblyFormTableBar">
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="details">详情</a>
</script>

<!--组件BOM表单头部操作-->
<!--assemblyFormTableBar-->
<script type="text/html" id="assemblyFormToolbar">
    <a class="layui-btn" lay-event="addItemBtn">添加物料</a>
</script>

<!--组件BOM表单操作-->
<!--assemblyFormTableBar-->
<script type="text/html" id="assemblyFormRightToolbar">
    <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete">删除</a>
    <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete">删除备选物料</a>
    {{# if(d.alternativeSkuName){ }}
    {{# if(d.isShow){ }}
    <a class="layui-btn layui-btn-xs" lay-event="save">保存</a>
    {{# }else{ }}
    <a class="layui-btn layui-btn-xs layui-btn-primary" lay-event="modify">修改</a>
    {{# } }}
    {{#  } }}
</script>

<!--添加物料BOM物料-->
<!--addItem-->
<!--<script type="text/html" id="addItem">
    <form lay-filter="addItemForm" class="layui-form model-form"
          style="padding: 5px 10px 0;height: calc(100% - 5px);overflow: hidden;">
        <div class="open-details-box" style="height: calc(100% - 65px); overflow-y: scroll;">
            &lt;!&ndash; 表格 &ndash;&gt;
            <table class="layui-table" id="addItemFormTable" lay-filter="addItemFormTable"></table>
        </div>
        <div class="layui-form-item text-right" style="margin-top: 20px">
            <button class="layui-btn" lay-filter="assemblyFormSubmit" lay-submit>保存BOM信息</button>
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
        </div>
    </form>
</script>-->

<!--BOM物料物料系列列表-->
<!--materialList-->
<script type="text/html" id="materialList">
    <div class="layui-fluid">
        <div class="layui-card">
            <div class="layui-card-body">
                <!-- 头部操作栏 -->
                <form class="layui-form toolbar">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label w-auto">物料名称：</label>
                            <div class="layui-input-inline mr0">
                                <input name="" class="layui-input" type="text"/>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button class="layui-btn icon-btn" lay-filter="materialListSubSearchLog" lay-submit
                                    type="button">搜索
                            </button>
                            <button id="materialListAddClose" class="layui-btn icon-btn" type="button">确认选择</button>
                        </div>
                    </div>
                </form>

                <!-- 表格 -->
                <table class="layui-table" id="materialListAddTable" lay-filter="materialListAddTable"></table>
            </div>
        </div>
    </div>
</script>


<!-- js部分 -->
<script>
    layui.use(['layer', 'form', 'table', 'admin', 'element'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var config = layui.config;
        var admin = layui.admin;
        var upload = layui.upload;
        let element = layui.element;

        form.render("select");

        // 渲染表格
        let insTb = table.render({
            elem: '#productDetailTable',
            url: config.base + 'enterprise/product/admin/productDetail/list',
            page: true,
            cellMinWidth: 100,
            cols: [[
                {type: 'numbers', title: '序号'}
                , {
                    field: 'productPic',
                    title: '图片',
                    templet: d => '<img src="' + d.productPic + '" style="height: 50px;width:auto;">'
                }
                ,  {field: 'skuCode', title: '物料编号'}
                , {field: 'skuSpecValueNames', title: '物料规格码'}
                , {field: 'productCode', title: '物料系列编号'}
                , {field: 'productType', title: '物料类型'}
                , {field: 'unitName', title: '基础单位'}
                , {field: 'unitId', title: '计量单位'}
                , {field: 'packId', title: '包装方式'}
                , {field: 'weightNumber', title: '重量'}
                , {field: 'deleted', title: '状态', templet: d => d.deleted ? '已删除' : '正常'}
                , {field: 'createTime', title: '创建时间'}
                , {field: 'updateTime', title: '变动时间'}
                , {align: 'center', toolbar: '#productDetailTableBar', title: '操作', width: 150}

                /*,{field: 'creatorName', title: '创建人'}
                ,{field: 'modifierName', sort: true, title: '修改人'}
                ,{field: 'productId', sort: true, title: '商品ID'}
                ,{field: 'sku', sort: true, title: '商品SKU'}
                ,{field: 'productPic', sort: true, title: '商品缩略图'}
                ,{field: 'skuName', sort: true, title: '物料名称'}
                ,{field: 'skuSpec', sort: true, title: '商品规格'}
                ,{field: 'enterpriceCode', sort: true, title: '企业货号'}
                ,{field: 'marketPrice', sort: true, title: '市场指导价'}
                ,{field: 'storePrice', sort: true, title: '商品店铺价'}
                ,{field: 'activityPrice', sort: true, title: '最低活动价'}
                ,{field: 'supplyPrice', sort: true, title: '平台供货价'}
                ,{field: 'stockNumber', sort: true, title: '库存数'}
                ,{field: 'barcode', sort: true, title: '商品条码'}
                ,{field: 'sortNumber', sort: true, title: '排序'}
                ,{field: 'settledCompanyId', sort: true, title: '入驻企业ID'}
                ,{field: 'createTime', sort: true, title: '创建时间'}
                ,{align: 'center', toolbar: '#productDetailTableBar', title: '操作', width: 200}*/
            ]],
            done: function (res, curr, count) {
                //移除按钮
                /*var menuButton = config.getMenuButton(location.hash);
                if (menuButton.indexOf("搜索") == -1) {
                    $('.layui-form.toolbar').remove();
                }
                if (menuButton.indexOf("修改") == -1) {
                    $("[lay-event='edit']").remove();
                }
                if (menuButton.indexOf("删除") == -1) {
                    $("[lay-event='del']").remove();
                }*/
            }
        });

        // 工具条点击事件
        table.on('tool(productDetailTable)', function (obj) {
            let data = obj.data;
            if (obj.event === 'edit') { //修改
                showEditModel(data);
            } else if (obj.event === 'del') { // 删除
                doDelete(obj);
            } else if (obj.event === 'details') {

            } else if (obj.event === 'assembly') {
                showAssembly(data);
            }
        });

        //监听排序
        table.on('sort(productDetailTable)', function (obj) {
            table.reload('productDetailTable', {
                initSort: obj
                , where: {
                    sort: obj.field
                    , order: obj.type
                }
            });
        });

        // 搜索
        form.on('submit(formSubSearchLog)', function (data) {
            insTb.reload({where: data.field, page: {curr: 1}}, 'data');
        });

        // 添加按钮点击事件
        $('#productDetailBtnAdd').click(function () {
            showEditModel();
        });

        // 显示编辑弹窗
        function showEditModel(data) {
            admin.open({
                type: 1,
                area: '860px',
                offset: '65px',
                title: data ? '修改物料明细表' : '添加物料明细表',
                content: $('#productDetailForm').html(),
                success: function () {
                    form.val('productDetailForm', data);
                    // 表单提交事件
                    form.on('submit(productDetailFormSubmit)', function (d) {
                        layer.load(2);
                        admin.req(data ? 'enterprise/product/admin/productDetail/update' : 'enterprise/product/admin/productDetail/add', d.field, function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {
                                layer.msg(res.msg, {icon: 1});
                                table.reload('productDetailTable');
                                layer.closeAll('page');
                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        }, data ? 'PUT' : 'POST');
                        return false;
                    });
                }
            });
        }

        // 删除
        function doDelete(obj) {
            layer.confirm('确定要删除吗？', {
                offset: '65px',
                skin: 'layui-layer-admin'
            }, function (i) {
                layer.close(i);
                layer.load(2);
                admin.req('enterprise/product/admin/productDetail/' + obj.data.id, {}, function (res) {
                    layer.closeAll('loading');
                    if (res.code == 200) {
                        layer.msg(res.msg, {icon: 1});
                        obj.del();
                    } else {
                        layer.msg(res.msg, {icon: 2});
                    }
                }, 'DELETE');
            });
        }

        // 导出excel
        $('#productDetailBtnExport').click(function () {
            var checkRows = table.checkStatus('productDetailTable');
            if (checkRows.data.length == 0) {
                layer.msg('请选择要导出的数据', {icon: 2});
            } else {
                table.exportFile(insTb.config.id, checkRows.data, 'xls');
            }
        });

        // BOM信息数据
        let materialTableData = new Map();

        //  组件BOM
        function showAssembly(_data) {
            admin.open({
                type: 1,
                area: ['1480px', '800px'],
                offset: '65px',
                title: '物料组件BOM',
                content: $('#assembly').html(),
                success: function () {
                    let assemblyTabTitleData = '', assemblyTabContentData = '', workingProcedureData;
                    materialTableData.clear();
                    layer.load(2);
                    let assemblyFormTB = table.render({
                        elem: '#assemblyFormTable',
                        data: [_data],
                        page: false,
                        cellMinWidth: 100,
                        cols: [[
                            {type: 'numbers', title: '序号'}
                            , {
                                field: 'productPic',
                                title: '图片',
                                templet: d => '<img src="' + d.productPic + '" style="height: 50px;width:auto;">'
                            }
                            ,  {field: 'skuCode', title: '物料编号'}
                            , {field: 'skuSpecValueNames', title: '物料规格码'}
                            , {field: 'productCode', title: '物料系列编号'}
                            , {field: 'productType', title: '物料类型'}
                            , {field: 'unitName', title: '基础单位'}
                            , {field: 'unitId', title: '计量单位'}
                            , {field: 'packId', title: '包装方式'}
                            , {field: 'weightNumber', title: '重量'}
                            , {field: 'deleted', title: '状态', templet: d => d.deleted ? '已删除' : '正常'}
                            , {field: 'createTime', title: '创建时间'}
                            , {field: 'updateTime', title: '变动时间'}
                            // , {align: 'center', toolbar: '#assemblyFormTableBar', title: '操作', width: 150}
                        ]],
                        done: function (res, curr, count) {
                        }
                    });
                    admin.reqSync('enterprise/product/admin/processInfo/list', {productTypeId: _data.productTypeId}, function (res) {
                        layer.closeAll('loading');
                        // 清空tab头部和内容区域
                        $('#assemblyTabTitle').html('');
                        $('#assemblyTabTitle').html('');
                        if (res.code === 200) {
                            workingProcedureData = res.data
                            res.data.forEach((item, index) => {
                                let titleStyle = '', contentStyle = '';
                                // 历史单位时长
                                let unitDuration = `<div class="layui-form-item">
                                            <label class="layui-form-label w-auto">历史单位时长</label>
                                            <div class="layui-input-inline">
                                                <input class="layui-input" value="${item.createTime}" style="border: none;color: red" readonly="true"/>
                                             </div>
                                           </div>`;
                                //历史单位成本
                                let unitCost = `<div class="layui-form-item">
                                            <label class="layui-form-label w-auto">历史单位成本</label>
                                            <div class="layui-input-inline">
                                                <input class="layui-input" value="${item.createTime}" style="border: none;color: red" readonly="true"/>
                                             </div>
                                           </div>`;
                                // 平均合格率
                                let average = `<div class="layui-form-item">
                                            <label class="layui-form-label w-auto">平均合格率</label>
                                            <div class="layui-input-inline">
                                                <input class="layui-input" value="${item.createTime}" style="border: none;color: red" readonly="true"/>
                                             </div>
                                           </div>`;
                                // 创建table
                                let assemblyTabContentTable = `<table class="layui-table" id="assemblyTabContentTable${index}" lay-filter="assemblyTabContentTable${index}"></table>`;
                                // tab样式
                                if (index === 0) {
                                    titleStyle = 'layui-this';
                                    contentStyle = 'layui-tab-item layui-show';
                                } else {
                                    titleStyle = '';
                                    contentStyle = 'layui-tab-item';
                                }
                                // tab头部
                                assemblyTabTitleData = '<li class="' + titleStyle + '">' + item.nodeNames + '</li>';
                                // tab对应的内容区域
                                assemblyTabContentData = '<div class="' + contentStyle + '">' + unitDuration + unitCost + average + assemblyTabContentTable + '</div>';
                                // 渲染tab头部和内容区域
                                $('#assemblyTabTitle').append(assemblyTabTitleData);
                                $('#assemblyTabContent').append(assemblyTabContentData);

                                materialTableData.set('assemblyTabContentTable' + index, '');
                                // table
                                materialTable('assemblyTabContentTable' + index, _data, item);
                            });
                        }
                    });

                    //tab 点击事件
                    element.on('tab(assemblyTable)', function (data) {
                    });

                    //保存BOM信息
                    form.on('submit(assemblyFormSubmit)', d => {
                        new Promise((resolve, reject) => {
                            let assemblyFormSubmitData = [];
                            resolve(assemblyFormSubmitData);
                            materialTableData.forEach((item, index) => {
                                item.forEach((item1, index) => {
                                    if (!item1.isShow) {
                                        let assemblyFormSubmitDataObj = {};
                                        assemblyFormSubmitDataObj.skuCode = item1.skuCode;
                                        assemblyFormSubmitDataObj.processId = item1.processId;

                                        assemblyFormSubmitDataObj.defaultMaterialSkuCode = item1.defaultMaterialSkuCode;
                                        // assemblyFormSubmitDataObj.defaultSkuName = item1.defaultSkuName;
                                        // assemblyFormSubmitDataObj.defaultProductType = item1.defaultProductType;
                                        assemblyFormSubmitDataObj.defaultUnit = item1.defaultUnit;
                                        assemblyFormSubmitDataObj.defaultNumber = item1.defaultNumber;

                                        assemblyFormSubmitDataObj.alternativeMaterialSkuCode = item1.alternativeMaterialSkuCode;
                                        // assemblyFormSubmitDataObj.alternativeSkuName = item1.alternativeSkuName;
                                        // assemblyFormSubmitDataObj.alternativeProductType = item1.alternativeProductType;
                                        assemblyFormSubmitDataObj.alternativeUnit = item1.alternativeUnit;
                                        assemblyFormSubmitDataObj.alternativeNumber = item1.alternativeNumber;

                                        assemblyFormSubmitDataObj.maxPrice = item1.maxPrice;
                                        assemblyFormSubmitDataObj.minPrice = item1.minPrice;
                                        assemblyFormSubmitData.push(assemblyFormSubmitDataObj)
                                    }
                                })
                            })
                        }).then(rData => {
                            if (rData.length == 0) {
                                workingProcedureData.forEach((item, index) => {
                                    rData.push({processId: item.id, skuCode: _data.skuCode})
                                })
                            }

                            layer.load(2);
                            admin.req('enterprise/product/admin/productProcessMaterial/add', JSON.stringify(rData), res => {
                                layer.closeAll('loading');
                                if (res.code === 200) {
                                    layer.msg(res.msg, {icon: 1});
                                    insTb.reload('productDetailTable');
                                    layer.closeAll('page');
                                } else {
                                    layer.msg(res.msg, {icon: 2});
                                }
                            }, 'POST', true, 'application/json; charset=utf-8')
                        });

                    })
                }
            })
        }

        let noAlternative = {};
        function materialTable(tableId, _productData, _workingProcedureData) {
            admin.reqSync('enterprise/product/admin/productProcessMaterial/list', {
                skuCode: _productData.skuCode,
                processId: _workingProcedureData.id
            }, function (res) {
                if (res.code === 200) {
                    res.data.forEach(item => {
                        item.isShow = false;
                        item.defaultUnitData = getProductUnit(item.defaultProductType);
                        item.alternativeUnitData = getProductUnit(item.alternativeProductType)
                    });
                    materialTableData.set(tableId, res.data)
                }
            });
            table.render({
                elem: '#' + tableId,
                toolbar: '#assemblyFormToolbar',
                defaultToolbar: false,
                data: materialTableData.get(tableId),
                limit: Number.MAX_VALUE,
                height: 500,
                page: false,
                cellMinWidth: 100,
                cols: [[
                    {type: 'numbers', title: '序号', width: 50}
                    , {
                        field: 'defaultSkuName',
                        title: '默认物料名称',
                        width: 200,
                        templet: d => d.defaultSkuName + '<br />(' + d.defaultMaterialSkuCode + ')'
                    }
                    , {
                        field: 'defaultUnit', title: '默认单位', width: 150, templet: d => {
                            let selectHTML = `<span style="display:${d.isShow == true ? 'none' : ''}">${d.defaultUnitName}</span>`;
                            selectHTML += `<div style="display:${d.isShow == true ? '' : 'none'}"><select name="defaultUnit">`;
                            selectHTML += '<option value="">默认单位</option>';
                            d.defaultUnitData.forEach(item => {
                                if (d.defaultUnit && d.defaultUnit == item.id) {
                                    selectHTML += '<option value="' + item.id + '" selected="">' + item.name + '</option>';
                                } else {
                                    selectHTML += '<option value="' + item.id + '">' + item.name + '</option>';
                                }
                            });
                            selectHTML += '</select></div>';
                            return selectHTML;
                        }
                    }
                    , {
                        field: 'defaultNumber',
                        title: '默认所需数量',
                        width: 120,
                        templet: d => {
                            return `<input type="text" class="layui-input ${d.isShow == true ? '' : 'inputBorderNone'}"
                                     name="defaultNumber" value="${d.defaultNumber}" onkeyup="this.value=this.value.replace(/^0(0+|\\d+)|[^\\d]+/g,'')"  minlength="1">`
                        }
                    }
                    , {
                        field: 'alternativeSkuName',
                        title: '备选物料',
                        width: 200,
                        templet: d => {
                            if (!d.alternativeMaterialSkuCode) {
                                return '<button class="layui-btn layui-btn-xs" type="button" lay-event="alternative">添加备用物料</button>';
                            }
                            return d.alternativeSkuName + '<br />(' + d.alternativeMaterialSkuCode + ')';
                        }
                    }
                    , {
                        field: 'alternativeUnit',
                        title: '备选物料单位',
                        width: 120,
                        templet: d => {
                            if (!d.alternativeMaterialSkuCode) {
                                return ''
                            }
                            let selectHTML = `<span style="display:${d.isShow == true ? 'none' : ''}">${d.alternativeUnitName}</span>`;
                            selectHTML += `<div style="display:${d.isShow == true ? '' : 'none'}"><select name="alternativeUnit">`;
                            selectHTML += '<option value="">备选物料单位</option>';
                            d.alternativeUnitData.forEach(item => {
                                if (d.alternativeUnit && d.alternativeUnit == item.id) {
                                    selectHTML += '<option value="' + item.id + '" selected="">' + item.name + '</option>';
                                } else {
                                    selectHTML += '<option value="' + item.id + '">' + item.name + '</option>';
                                }
                            });
                            selectHTML += '</select></div>';
                            return selectHTML;
                        }
                    }
                    , {
                        field: 'alternativeNumber',
                        title: '备选物料所需数量',
                        width: 120,
                        templet: d => {
                            if (!d.alternativeMaterialSkuCode) {
                                return ''
                            }
                            return `<input type="text" class="layui-input ${d.isShow == true ? '' : 'inputBorderNone'}"
                                     name="alternativeNumber" value="${d.alternativeNumber}" onkeyup="this.value=this.value.replace(/^0(0+|\\d+)|[^\\d]+/g,'')"  minlength="1">`
                        }
                    }
                    , {field: '', title: '可替物料数', width: 80}
                    , {field: 'minPrice', title: '最低单价', width: 80}
                    , {field: 'maxPrice', title: '最高单价', width: 80}
                    , {
                        align: 'left', title: '操作', width: '250',
                        // toolbar: '#assemblyFormRightToolbar',
                        templet: d => {
                            let delBnt = '<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete">删除</a>';
                            let spareDelBtn = '<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="spareDelete">删除备选物料</a>';
                            if (!d.alternativeMaterialSkuCode) {
                                if (d.isShow) {
                                    return delBnt
                                } else {
                                    return delBnt
                                }
                            } else {
                                if (d.alternativeSkuName) {
                                    if (d.isShow) {
                                        return delBnt + spareDelBtn + '<a class="layui-btn layui-btn-xs" lay-event="save">保存</a>'
                                    } else {
                                        return delBnt + spareDelBtn + '<a class="layui-btn layui-btn-xs layui-btn-primary" lay-event="modify">修改</a>'
                                    }
                                }
                            }
                        }
                    }
                    // toolbar: '#assemblyFormRightToolbar',
                    /*<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete">删除</a>
                    <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete">删除备选物料</a>
                    {{# if(d.alternativeSkuName){ }}
                    {{# if(d.isShow){ }}
                    <a class="layui-btn layui-btn-xs" lay-event="save">保存</a>
                        {{# }else{ }}
                    <a class="layui-btn layui-btn-xs layui-btn-primary" lay-event="modify">修改</a>
                        {{# } }}
                    {{#  } }}*/

                ]],
                done: function (res, curr, count) {

                }
            });

            // 头工具栏事件
            table.on('toolbar(' + tableId + ')', function (obj) {
                if (obj.event === 'addItemBtn') { //addItemBtn 添加物料
                    showMaterialList(tableId, 'default', '-1', _productData, _workingProcedureData);
                }

            });
            // 工具条点击事件
            table.on('tool(' + tableId + ')', function (obj) {
                let data = obj.data;
                if (obj.event === 'alternative') { //  添加备用物料
                    noAlternative= {};
                    noAlternative = data;
                    console.log(noAlternative)
                    showMaterialList(tableId, 'alternative', obj.tr.index(), _productData, _workingProcedureData);
                } else if (obj.event === 'delete') { // 删除
                    let newMaterialTableData = materialTableData.get(tableId);
                    newMaterialTableData.splice(obj.tr.index(), 1);
                    materialTableData.set(tableId, newMaterialTableData);
                    table.reload(tableId, {data: materialTableData.get(tableId)});
                } else if (obj.event === 'save') { // 保存
                    if (materialTableData.get(tableId)[obj.tr.index()].defaultUnit == '') {
                        layer.msg('请选择默认单位', {icon: "5"});
                        return false
                    } else if (materialTableData.get(tableId)[obj.tr.index()].defaultNumber == '') {
                        layer.msg('请输入默认所需数量', {icon: "5"});
                        return false
                    } else if (materialTableData.get(tableId)[obj.tr.index()].alternativeUnit == '') {
                        layer.msg('请选择备选物料单位', {icon: "5"});
                        return false
                    } else if (materialTableData.get(tableId)[obj.tr.index()].alternativeNumber == '') {
                        layer.msg('请输入备选物料所需数量', {icon: "5"});
                        return false
                    }

                    let newMaterialTableData = materialTableData.get(tableId);
                    newMaterialTableData[obj.tr.index()].isShow = false;
                    materialTableData.set(tableId, newMaterialTableData);
                    table.reload(tableId, {data: materialTableData.get(tableId)});
                } else if (obj.event === 'modify') { // 修改
                    let newMaterialTableData = materialTableData.get(tableId);
                    newMaterialTableData[obj.tr.index()].isShow = true;
                    materialTableData.set(tableId, newMaterialTableData);
                    table.reload(tableId, {data: materialTableData.get(tableId)});
                }else if (obj.event === 'spareDelete'){// 删除备选物料
                    let newMaterialTableData = materialTableData.get(tableId);
                    // 删除备选物料的值
                    delete newMaterialTableData[obj.tr.index()].alternativeMaterialSkuCode;
                    delete newMaterialTableData[obj.tr.index()].alternativeNumber;
                    delete newMaterialTableData[obj.tr.index()].alternativeProductType;
                    delete newMaterialTableData[obj.tr.index()].alternativeSkuName;
                    delete newMaterialTableData[obj.tr.index()].alternativeUnit;
                    delete newMaterialTableData[obj.tr.index()].alternativeUnitData;
                    delete newMaterialTableData[obj.tr.index()].alternativeUnitName;
                    delete newMaterialTableData[obj.tr.index()].maxPrice;
                    delete newMaterialTableData[obj.tr.index()].minPrice;
                    newMaterialTableData[obj.tr.index()].isShow = true;
                    materialTableData.set(tableId, newMaterialTableData);
                    table.reload(tableId, {data: materialTableData.get(tableId)});
                }
            });

            $("body").delegate("[lay-id='" + tableId + "'] input[name='defaultNumber']", "change", function () {
                let materialTableDataNew = materialTableData.get(tableId);
                let assemblyTabContentTableKey = tableId;
                materialTableDataNew[$(this).parents('tr').index()].defaultNumber = $(this).val();
                materialTableData.set(assemblyTabContentTableKey, materialTableDataNew);
            });
            $("body").delegate("[lay-id='" + tableId + "'] input[name='alternativeNumber']", "change", function () {
                let materialTableDataNew = materialTableData.get(tableId);
                let assemblyTabContentTableKey = tableId;
                materialTableDataNew[$(this).parents('tr').index()].alternativeNumber = $(this).val();
                materialTableData.set(assemblyTabContentTableKey, materialTableDataNew);
            });
            form.on("select", function (data) {
                let assemblyTabContentTableKey = $(data.elem).parents('.layui-form').attr('lay-id');
                if ($(data.elem).attr('name') == 'defaultUnit') {
                    let materialTableDataNew = materialTableData.get(assemblyTabContentTableKey);
                    materialTableDataNew[$(data.elem).parents('tr').index()].defaultUnit = data.value;
                    materialTableDataNew[$(data.elem).parents('tr').index()].defaultUnitName = data.elem[data.elem.selectedIndex].text;
                    materialTableData.set(assemblyTabContentTableKey, materialTableDataNew);
                } else if ($(data.elem).attr('name') == 'alternativeUnit') {
                    let materialTableDataNew = materialTableData.get(assemblyTabContentTableKey);
                    materialTableDataNew[$(data.elem).parents('tr').index()].alternativeUnit = data.value;
                    materialTableDataNew[$(data.elem).parents('tr').index()].alternativeUnitName = data.elem[data.elem.selectedIndex].text;
                    materialTableData.set(assemblyTabContentTableKey, materialTableDataNew);
                }
            });
        }

        let currentPageData = [];
        let checkedMap = new Map();
        let checkedData = [];

        // BOM物料物料系列列表
        function showMaterialList(_tableId, _type, _cursor, _productData, _workingProcedureData) {
            checkedMap.clear();
            checkedData = [];
            currentPageData = [];
            let showMaterialListPopUp = admin.open({
                type: 1,
                area: ['1400px', '750px'],
                offset: '85px',
                title: 'BOM物料物料系列列表',
                content: $('#materialList').html(),
                success: function () {
                    table.render({
                        elem: '#materialListAddTable',
                        url: config.base + 'enterprise/product/admin/productDetail/list',
                        page: true,
                        cellMinWidth: 100,
                        cols: [[
                            {type: _type == 'default' ? 'checkbox' : 'radio'}
                            , {
                                field: 'productPic',
                                title: '图片',
                                templet: d => '<img src="' + d.productPic + '" style="height: 50px;width:auto;">'
                            }
                            , {field: 'skuName', title: '物料名称'}
                            , {field: 'skuCode', title: '物料编号'}
                            , {field: 'stockNumber', title: '物料数量'}
                            , {field: 'productType', title: '物料类型'}
                            , {field: 'weightNumber', title: '重量'}
                            , {field: 'deleted', title: '状态', templet: d => d.deleted ? '已删除' : '正常'}
                            , {field: 'createTime', title: '创建时间'}
                            /*   , {align: 'center', toolbar: '#assemblyFormTableBar', title: '操作', width: 150}*/
                        ]],
                        parseData:function(res){
                            res.data.forEach((item , index) => {
                                if (item.skuCode == _productData.skuCode) {
                                    res.data.splice(index, 1);
                                }
                            });

                            return res;
                        },
                        done: function (res, curr, count) {
                            if (_type == 'default') {
                                currentPageData = res.data;
                                let isCheckAll = true;
                                let isAllGenOrder = true;
                                materialTableData.get(_tableId).forEach(item => {
                                    checkedMap.set(item.defaultMaterialSkuCode, item);
                                });

                                for (let k = 0; k < res.data.length; k++) {
                                    res.data[k].LAY_CHECKED = true;
                                    let index = res.data[k]['LAY_TABLE_INDEX'];
                                    let checkbox = $('#' + 'materialListAddTable' + '').next().find('tr[data-index=' + index + '] input[type="checkbox"]');
                                    if (checkedMap.get(res.data[k].skuCode)) {
                                        checkbox.prop('checked', true).next().addClass('layui-form-checked');
                                        $('div[lay-id="materialListAddTable"] tr').eq(index + 1).addClass('materialListAddTableTrDisable')

                                    } else {
                                        isCheckAll = false;
                                    }
                                    if (checkedMap.get(res.data[k].skuCode)) {
                                        $(checkbox[0]).parent().remove();
                                    } else {
                                        isAllGenOrder = false;
                                    }
                                }
                                if (isCheckAll) {
                                    $('[lay-filter="layTableAllChoose"]').prop('checked', true).next().addClass('layui-form-checked');
                                }
                                if (isAllGenOrder) {
                                    $($('[lay-filter="layTableAllChoose"]')[0]).parent().hide();
                                } else {
                                    $($('[lay-filter="layTableAllChoose"]')[0]).parent().show();
                                }
                            }else if (_type == 'alternative'){
                                for (let k = 0; k < res.data.length; k++){
                                    let index = res.data[k]['LAY_TABLE_INDEX'];
                                    let radio = $('#' + 'materialListAddTable' + '').next().find('tr[data-index=' + index + '] input[type="radio"]');

                                    if( res.data[k].skuCode == noAlternative.defaultMaterialSkuCode){
                                        $(radio[0]).parent().remove();
                                        $('div[lay-id="materialListAddTable"] tr').eq(index + 1).addClass('materialListAddTableTrDisable')
                                    }
                                }
                            }
                        }
                    });

                    table.on('checkbox(materialListAddTable)', function (obj) {
                        if (_type == 'default') {
                            let data = obj.data;
                            if (obj.type == 'all') {
                                if (obj.checked) {
                                    var checkStatus = table.checkStatus('materialListAddTable');
                                    var checkedAllData = checkStatus.data;
                                    checkedAllData.forEach(item => {
                                        if (checkedMap.get(item.skuCode) == undefined) {
                                            checkedData.push(item);
                                            checkedMap.set(item.skuCode, item.id);
                                        }

                                    })


                                } else {
                                    currentPageData.forEach(item => {
                                        if (checkedMap.get(item.skuCode) != undefined) {
                                            checkedData = checkedData.filter(item2 => {
                                                if (item.skuCode == item2.skuCode) {
                                                    return false;
                                                }
                                                return true;
                                            })
                                        }
                                        checkedMap.delete(item.skuCode);

                                    })
                                }
                            } else {  // 没有点击全选按钮
                                if (obj.checked) { // 选择多选框
                                    if (checkedMap.get(data.skuCode) == undefined) {
                                        checkedData.push(data);
                                    }
                                    checkedMap.set(data.skuCode, data);

                                } else {
                                    if (checkedMap.get(data.skuCode) != undefined) {
                                        checkedData = checkedData.filter(item => {
                                            if (item.skuCode == data.skuCode) {
                                                return false;
                                            }
                                            return true;
                                        })
                                    }
                                    checkedMap.delete(data.skuCode);
                                }

                                let isAllChecked = true; // 设置全选按钮的默认值
                                currentPageData.forEach(item => { // 遍历当前页面所有的值
                                    if (checkedMap.get(item.skuCode) == undefined) { // 如果有一个值不存在checkedMap中 全选按钮则为false
                                        isAllChecked = false;
                                    }

                                });

                                //全选按钮是否选中
                                if (isAllChecked) {
                                    $('[lay-filter="layTableAllChoose"]').prop('checked', true).next().addClass('layui-form-checked');
                                } else {
                                    $('[lay-filter="layTableAllChoose"]').prop('checked', false).next().removeClass('layui-form-checked');
                                }
                            }
                        }

                    });

                    $('#materialListAddClose').click(function () {
                        let checkStatus = table.checkStatus('materialListAddTable');
                        if (_type == 'default') {
                            checkStatus.data = checkedData;
                        }
                        if (checkStatus.data.length == 0) {
                            layer.msg("请选择BOM物料物料", {icon: 2, time: 1000});
                        } else {
                            let checkStatusObj = {};
                            checkStatusObj.isShow = true;
                            if (_type == 'default') {
                                let checkStatusArray = [];
                                /*checkStatusObj.defaultSkuName = checkStatus.data[0].skuName;
                                checkStatusObj.defaultMaterialSkuCode = checkStatus.data[0].skuCode;
                                checkStatusObj.defaultProductType = checkStatus.data[0].productTypeId;
                                checkStatusObj.defaultUnit = checkStatus.data[0].unitId;
                                checkStatusObj.defaultUnitData = getProductUnit(checkStatus.data[0].productTypeId);
                                checkStatusObj.defaultPrice = checkStatus.data[0].costPrice;
                                checkStatusObj.defaultNumber = 0;
                                checkStatusObj.skuCode = _productData.skuCode;
                                checkStatusObj.processId = _workingProcedureData.id;
                                console.log([checkStatusObj])
                                materialTableData.set(_tableId, [...materialTableData.get(_tableId), ...[checkStatusObj]]);*/
                                checkStatus.data.forEach((item, index) => {
                                    checkStatusObj = {};
                                    checkStatusObj.isShow = true;
                                    checkStatusObj.defaultSkuName = item.skuName;
                                    checkStatusObj.defaultMaterialSkuCode = item.skuCode;
                                    checkStatusObj.defaultProductType = item.productTypeId;
                                    checkStatusObj.defaultUnit = item.unitId;
                                    checkStatusObj.defaultUnitData = getProductUnit(item.productTypeId);
                                    checkStatusObj.defaultPrice = item.costPrice;
                                    checkStatusObj.defaultNumber = 0;
                                    checkStatusObj.skuCode = _productData.skuCode;
                                    checkStatusObj.processId = _workingProcedureData.id;
                                    checkStatusArray.push(checkStatusObj)
                                });
                                console.log(checkStatusArray)
                                materialTableData.set(_tableId, [...materialTableData.get(_tableId), ...checkStatusArray]);


                            } else if (_type == 'alternative') {
                                let materialTableDataNew = materialTableData.get(_tableId);
                                checkStatusObj.alternativeSkuName = checkStatus.data[0].skuName;
                                checkStatusObj.alternativeMaterialSkuCode = checkStatus.data[0].skuCode;
                                checkStatusObj.alternativeProductType = checkStatus.data[0].productTypeId;
                                checkStatusObj.alternativeUnit = checkStatus.data[0].unitId;
                                checkStatusObj.alternativeUnitData = getProductUnit(checkStatus.data[0].productTypeId);
                                checkStatusObj.alternativePrice = checkStatus.data[0].costPrice;
                                checkStatusObj.alternativeNumber = 0;
                                checkStatusObj.maxPrice = materialTableDataNew[_cursor].defaultPrice >= checkStatusObj.alternativePrice ? materialTableDataNew[_cursor].defaultPrice : checkStatusObj.alternativePrice;
                                checkStatusObj.minPrice = materialTableDataNew[_cursor].defaultPrice < checkStatusObj.alternativePrice ? materialTableDataNew[_cursor].defaultPrice : checkStatusObj.alternativePrice;

                                materialTableDataNew[_cursor] = Object.assign(materialTableData.get(_tableId)[_cursor], checkStatusObj);
                                materialTableData.set(_tableId, materialTableDataNew);
                            }

                            layer.close(showMaterialListPopUp);
                            table.reload(_tableId, {data: materialTableData.get(_tableId)});
                        }
                    })
                }
            });
        }

        function getProductUnit(_productType) {
            let data = [];
            admin.reqSync('enterprise/product/admin/productUnit/list', {productType: _productType}, res => {
                if (res.code === 200) {
                    data = res.data
                }
            });
            return data
        }
    });
</script>